#使用默认参数，对四种核函数进行预测，比较准确率

from sklearn.datasets import load_breast_cancer		 #导入肺癌数据集
from sklearn.svm import SVC                          #导入支持向量机分类模块
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd

dataset = load_breast_cancer()
x,y=dataset.data, dataset.target
print(x.shape)
print(x)


#数据标准化

from sklearn.preprocessing import StandardScaler
x = StandardScaler().fit_transform(x)
print(x)


#训练模型

#分割数据集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=420)

#分别计算四种核函数的准确率
Kernel=['linear','poly','rbf','sigmoid']
for kernel in Kernel:
   model=SVC(kernel=kernel,gamma="auto",degree=1)
   model.fit(x_train,y_train)
   pred = model.predict(x_test)
   ac = accuracy_score(y_test, pred)
   print(f'当使用{kernel}核函数时， 模型准确率为:{ac}')


#寻找多项式核函数的最优参数

from sklearn.model_selection import StratifiedShuffleSplit		    #导入分层抽样方法
from sklearn.model_selection import GridSearchCV				    #导入网格搜索方法
gamma_range = np.logspace(-10,1,20)
coef0_range = np.linspace(0,5,10)
param_grid = dict(gamma=gamma_range,coef0 = coef0_range)
cv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=420)
model = SVC(kernel='poly', degree=1)                                            #对样本进行分层抽样
grid = GridSearchCV(model, param_grid = param_grid,cv=cv)	                    #使用网格搜索法寻找参数的最优值
grid.fit(x,y)
print(f'最优参数值为: {grid.best_params_}')
print(f'选取该参数值时，模型的预测准确率为：{grid.best_score_}')


#高斯核函数（rbf）的最优参数

score = []
gamma_range = np.logspace(-10, 1, 50)
for i in gamma_range:
    model = SVC(kernel='rbf', gamma=i)
    model.fit(x_train, y_train)
    pred = model.predict(x_test)
    ac = accuracy_score(y_test, pred)
    score.append(ac)

import matplotlib.pyplot as plt
plt.plot(gamma_range, score)
plt.show()
max_score = max(score)
print(f'参数gamma的最优值为: {gamma_range[score.index(max_score)]}')
print(f'选取该参数值时， 模型的准确率为:{max_score}')
